﻿using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static ConcurrentBag<Student> students = new ConcurrentBag<Student>();
    static Mutex mutex = new Mutex(); // 创建互斥锁对象

    static async Task Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            Student student = new Student()
            {
                Id = i,
            };
            students.Add(student);
        }
        await Task.Delay(1000);

        Task.Run(() =>
        {
            mutex.WaitOne(); // 获取互斥锁
            try
            {
                Student student = students.Where(x => x.Id == 0).FirstOrDefault();
                if (string.IsNullOrEmpty(student.Name))
                {
                    student.Name = "123";
                    Console.WriteLine("设置成功");
                }
                else
                {
                    Console.WriteLine("已有数据");
                }
            }
            finally
            {
                mutex.ReleaseMutex(); // 释放互斥锁
            }
        });

        Task.Run(() =>
        {
            mutex.WaitOne(); // 获取互斥锁
            try
            {
                Student student = students.Where(x => x.Id == 0).FirstOrDefault();
                if (string.IsNullOrEmpty(student.Name))
                {
                    student.Name = "123";
                    Console.WriteLine("设置成功");
                }
                else
                {
                    Console.WriteLine("已有数据");
                }
            }
            finally
            {
                mutex.ReleaseMutex(); // 释放互斥锁
            }
        });

        Task.Run(() =>
        {
            mutex.WaitOne(); // 获取互斥锁
            try
            {
                Student student = students.Where(x => x.Id == 0).FirstOrDefault();
                if (string.IsNullOrEmpty(student.Name))
                {
                    student.Name = "123";
                    Console.WriteLine("设置成功");
                }
                else
                {
                    Console.WriteLine("已有数据");
                }
            }
            finally
            {
                mutex.ReleaseMutex(); // 释放互斥锁
            }
        });

        Console.ReadLine();
    }
}

class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}